package auth;

import controller.SessionAttribute;
import entity.OrdersLocal;
import entity.OrdersLocalHome;
import entity.UsersLocal;
import entity.UsersLocalHome;
import helper.SimpleJSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import transfer.Order;
import transfer.OrderState;
import transfer.User;

/**
 *
 * @author Oleh
 */
public class SignIn extends HttpServlet {

    public static final String answer = "answer";
    public static final String ok = "OK";
    public static final String wrong = "WRONG";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String login = request.getParameter("login");
        String password = request.getParameter("password");
        PrintWriter out = null;
        try {
            InitialContext context = new InitialContext();
            UsersLocalHome homeUser = (UsersLocalHome) context.lookup("java:comp/env/Users");
            boolean result = homeUser.isLoginAndPasswordExist(login, password);
            SimpleJSONObject json = new SimpleJSONObject();
            if (result) {
                json.addProperty(answer, ok);
                UsersLocal localUser = homeUser.findByLogPass(login, password);
                User user= localUser.getUser();
                HttpSession session = request.getSession();
                session.setAttribute(SessionAttribute.SIGN_IN, new Boolean(true));
                session.setAttribute(SessionAttribute.USER, user);
                OrdersLocalHome homeOrder = (OrdersLocalHome) context.lookup("java:comp/env/Orders");
                boolean cartExist = homeOrder.isCartExist(user);
                Order cart = null;
                if (cartExist) {
                    OrdersLocal localOrder = homeOrder.findCart(user);
                    cart = localOrder.getOrder();
                } else {
                    cart = new Order();
                    cart.setCustomer(user);
                    cart.setOrderState(OrderState.ENTERING);
                    cart.setTotalCost(new Double(0));
                    cart.setIsSubscribed(Boolean.FALSE);
                    cart.setCommodities(new HashMap());
                    OrdersLocal localOrder = homeOrder.create(cart);
                    cart = localOrder.getOrder();
                }
                session.setAttribute(SessionAttribute.CART, cart);
            } else {
                json.addProperty(answer, wrong);
            }
            response.setContentType("application/json;charset=UTF-8");
            out = response.getWriter();
            out.println(json);

        }  catch (FinderException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (CreateException ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
